import requests
import time
import json
import hashlib
from weather.config import weather_config
import uuid

base_url = 'https://restapi.getui.com/v2/'


def gt_push(title, msg, intent, auth_token):
    request_id = str(uuid.uuid4())[:31]
    body = {
        "request_id": request_id,
        "settings": {
                "ttl": 3600000
        },
        # 'audience': 'all',
        'audience': {
            'cid': [
                'd6cf6bdcb8c801f8d6f02ccd0203c763'
            ]
        },
        'push_channel': {
            'android': {
                'ups': {
                    'notification': {
                        'title': title,
                        'body': msg,
                        'click_type': 'intent',
                        'intent': intent
                    }
                }
            }
        },
        "push_message": {
            "notification": {
                "title": title,
                "body": msg,
                'click_type': 'intent',
                'intent': intent
            }
        }
    }

    batch_push(auth_token, body)


def get_token():
    gt = weather_config.get('gt')
    app_key = gt.get('app_key')
    master_secret = gt.get('master_secret')

    url = _get_url('auth')
    ts = int(round(time.time() * 1000))
    sign = hashlib.sha256(f'{app_key}{ts}{master_secret}'.encode('utf-8')).hexdigest()
    body = {
        'sign': sign,
        'timestamp': f'{ts}',
        'appkey': app_key
    }
    resp = requests.post(url=url, headers={'content-type': 'application/json;charset=utf-8'},
                         data=json.dumps(body))
    resp = resp.json()
    if resp.get('code') == 0:
        token = resp['data']['token']
        return token
    else:
        print('get token fail, resp: {}'.format(resp))
        raise Exception()


def batch_push(token, body):
    # url = _get_url('push/all')
    url = _get_url('push/single/cid')
    resp = requests.post(url=url, headers={'token': token,
                                           'content-type': 'application/json;charset=utf-8'},
                         data=json.dumps(body))
    resp = resp.json()
    if not resp.get('code') == 0:
        print('batch push fail, resp: {}'.format(resp))
        raise Exception()


def _get_url(api):
    gt = weather_config.get('gt')
    app_id = gt.get('app_id')
    url = base_url + app_id + '/' + api
    return url
